/**
 * Licensed to the Apache Software Foundation （ASF） under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * （the "License"）； you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * <p>
 * https://www.q3z3.com
 * QQ : 939313737
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.platform.modules.sys.service.impl;

import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.platform.common.shiro.ShiroUtils;
import com.platform.modules.sys.domain.SysUser;
import com.platform.modules.sys.service.SysOnlineService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 系统用户表 服务层实现
 * </p>
 */
@Service("sysOnlineService")
public class SysOnlineServiceImpl implements SysOnlineService {

    @Resource
    private SessionDAO sessionDAO;

    @Override
    public List<SysUser> queryList(SysUser searchUser) {
        // 查询全部用户
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        List<SysUser> userList = new ArrayList<>();
        for (Session session : sessions) {
            if (session == null) {
                continue;
            }
            Object authenticated = session.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
            if (!Boolean.valueOf(String.valueOf(authenticated))) {
                continue;
            }
            Object principals = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principals == null) {
                continue;
            }
            SysUser user = new SysUser();
            BeanUtils.copyProperties(((SimplePrincipalCollection) principals).getPrimaryPrincipal(), user);
            // 过滤admin
            if (ShiroUtils.isAdmin(user)) {
                continue;
            }
            String sessionId = session.getId().toString();
            // 过滤自己
            if (ShiroUtils.getSessionId().equals(sessionId)) {
                continue;
            }
            Date startTimestamp = session.getStartTimestamp();
            user.setStartTimestamp(startTimestamp);
            user.setHost(session.getHost());
            user.setSessionId(sessionId);
            user.setRunTime(DateUtil.formatBetween(DateUtil.between(startTimestamp, DateUtil.date(), DateUnit.MS), BetweenFormater.Level.SECOND));
            userList.add(user);
        }
        // 搜索过滤
        if (!StringUtils.isEmpty(searchUser.getUsername())) {
            userList = userList.stream().filter(user -> user.getUsername().contains(searchUser.getUsername())).collect(Collectors.toList());
        }
        if (searchUser.getStatus() != null) {
            userList = userList.stream().filter(user -> user.getStatus().equals(searchUser.getStatus())).collect(Collectors.toList());
        }
        return userList;
    }

    @Override
    public void offline(String sessionId) {
        // 查询全部用户
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            if (session == null) {
                continue;
            }
            if (sessionId.equals(session.getId().toString())) {
                session.setTimeout(0);
                session.setAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY, false);
                sessionDAO.delete(session);
                return;
            }
        }
    }
}
